/**
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-2-23 下午5:12:01 
 * @version:  V1.0 
 */

package artid.com.arttogoa.keeponrecord;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import artid.com.arttogoa.BaseActivity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.adapter.ArtRecordAdapter;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.ArtRecordstate;
import artid.com.arttogoa.parser.RecordList;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullToRefreshLayout;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullableListView;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullToRefreshLayout.OnRefreshListener;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;

/**
 * TODO<备案列表>
 * 
 * @author 熊彬
 * @data: 2016-2-23 下午5:12:01
 * @version: V1.0
 */
public class ArtRecordActivity extends BaseActivity implements
		android.view.View.OnClickListener {
	private ArtRecordAdapter adapter;
	private RelativeLayout type;
	private TextView title_text, apply;
	private TextView all, doing, torecord, norecord, info;
	private ImageView mimage;
	private PullableListView listview;
	private PullToRefreshLayout mPullLayout;
	private boolean isRefreshed = false;// 是否刷新
	private int page = 1;
	private List<RecordList> list;
	private List<RecordList> more_list;
	private String reqAtristListType = "";// 备案列表状态 默认全部
	private String userPhone;
	private RelativeLayout optionsLayout, phoneOption, filingOption;
	private ImageView optionClear;
	private LinearLayout llOption;
	public static final String _PHONE = "phoneOption";
	public static final String _FILING = "filingOption";

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.example.artworkarta.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_art_record);
		setContent(this, getIntent());
		setBack();
		mTittle.setText("艺术品备案");
		hint = (LinearLayout) findViewById(R.id.ll_hint);
		userPhone = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue("Phone", "");
		initData();
		setArtHeight();
	}

	/** 测量状态栏 */
	private ViewTreeObserver viewTreeObserver;
	private int state_height;
	private int window_height;

	private void setArtHeight() {
		// TODO Auto-generated method stub
		String size = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue(Cache.ART_SIZE, "");
		if (TextUtils.isEmpty(size)) {
			window_height = Integer.valueOf(NetUtils.getDisplayMetrics(this)
					.get(NetUtils.DM_HEIGHT));
			/** 测量状态栏高度 **/
			viewTreeObserver = optionsLayout.getViewTreeObserver();
			viewTreeObserver
					.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

						@Override
						public void onGlobalLayout() {
							if (state_height == 0) {
								// 获取状况栏高度
								Rect frame = new Rect();
								getWindow().getDecorView()
										.getWindowVisibleDisplayFrame(frame);
								state_height = frame.top;
								window_height = window_height - state_height;
							}
						}
					});
			int infoHeight = NetUtils.dip2px(mContext, 44 + 45);
			int listHeight = NetUtils.dip2px(mContext, 87);
			/** 最终的高度为：屏幕高度-状态栏高度-提示文字高度-列表高度 */
			window_height = window_height - infoHeight - listHeight;
			MySharedPreferences.getMySharedPreferences(mContext).setValue(
					Cache.ART_SIZE, String.valueOf(window_height));
		}
	}

	// /**
	// * 确认提交申请备案
	// */
	// private void comNetwork() {
	// // TODO Auto-generated method stub12
	// String uri = Cache.saveartRecord;
	// // System.out.println("params=" + params.toString());
	// String id = MySharedPreferences.getMySharedPreferences(mContext)
	// .getValue(Cache.ART_ID, "");
	// VolleyBasic.getInstance(ArtRecordActivity.this).post(false, false, uri,
	// VolleyMap.getInstance().saveartRecord(id), UserItem.class,
	// new VolleyCallback() {6.,
	// public void onSuccess(VolleyData vd) {
	// // AlertUtils.dismiss();
	// // TODO
	// // Auto-generated
	// // method stub
	// Log.i("my上传3", "第二个============" + vd.getJson());
	// try {
	// JSONObject jo = new JSONObject(vd.getJson());
	// if (jo.optString("ret").equals("1")) {
	// MySharedPreferences.getMySharedPreferences(
	// mContext).setValue(Cache.ARTREC_STATUS,
	// "no");
	// reqAtristListNumData();// 艺术品备案状态列表及数量
	//
	// } else {
	//
	// }
	//
	// } catch (JSONException e) {
	// // TODO
	// // Auto-generated
	// // catch
	// // block
	// e.printStackTrace();
	// }
	// }
	//
	// public void onError(VolleyError volleyError) {
	// String is = MySharedPreferences.getMySharedPreferences(
	// mContext).getValue(Cache.artIsLoad, "no");
	// if (is.equals("yes")) {
	// reqAtristListNumData();
	// } else {
	// AlertUtils.disMissLoding();
	// }
	//
	// }
	// });
	// }

	/**
	 * 	
	 */
	private void initData() {
		// TODO Auto-generated method stub
		// rightMenu.setVisibility(View.VISIBLE);
		mContext = this;
		list = new ArrayList<RecordList>();
		more_list = new ArrayList<RecordList>();
		listview = (PullableListView) findViewById(R.id.art_record_listivew);
		mPullLayout = (PullToRefreshLayout) findViewById(R.id.art_record_refresh_view);
		type = (RelativeLayout) findViewById(R.id.ll_news_type);

		llOption = (LinearLayout) findViewById(R.id.lin_lin);
		optionsLayout = (RelativeLayout) findViewById(R.id.rel_filing_options);
		optionsLayout.setVisibility(View.GONE);
		phoneOption = (RelativeLayout) findViewById(R.id.rel_p);
		filingOption = (RelativeLayout) findViewById(R.id.rel_m);
		optionsLayout.setOnClickListener(this);
		phoneOption.setOnClickListener(this);
		filingOption.setOnClickListener(this);
		optionClear = (ImageView) findViewById(R.id.iv_options_clear);

		title_text = (TextView) findViewById(R.id.title_text);
		info = (TextView) findViewById(R.id.tv_info);
		apply = (TextView) findViewById(R.id.title_right);
		title_text.setText("艺术品备案");
		mimage = (ImageView) findViewById(R.id.back_btn);// 返回
		mTittle.setOnClickListener(this);
		type.setOnClickListener(this);
		title_text.setOnClickListener(this);
		mimage.setOnClickListener(this);
		all = (TextView) findViewById(R.id.all);// 全部返回
		doing = (TextView) findViewById(R.id.doing);// 审核中
		torecord = (TextView) findViewById(R.id.to_record);// 已备案
		norecord = (TextView) findViewById(R.id.no_record);// 未通过审核
		all.setOnClickListener(this);
		apply.setOnClickListener(this);
		apply.setVisibility(View.VISIBLE);
		doing.setOnClickListener(this);
		torecord.setOnClickListener(this);
		norecord.setOnClickListener(this);

		/**
		 * 判断是否认证，未认证不可申请备案
		 */
		if ("2".equals(AppUtil.getUser().getIs_auth())
				|| "0".equals(AppUtil.getUser().getIs_auth())
				|| "-1".equals(AppUtil.getUser().getIs_auth())) {
			info.setVisibility(View.VISIBLE);
			apply.setVisibility(View.GONE);
			title_text.setClickable(false);
			title_text.setEnabled(false);
		}
		mPullLayout.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				// 下拉刷新
				page = 1;
				isRefreshed = true;
				reqAtristListData(reqAtristListType);// 备案列表
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				// pullToRefreshLayout.setBottomDismiss();
				// 上拉加载
				page++;
				reqAtristListData(reqAtristListType);// 备案列表
			}
		});
		String is = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue(Cache.artIsLoad, "no");
		if (!is.equals("yes")) {
			reqAtristListNumData();// 艺术品备案状态列表及数量
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		String is = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue(Cache.artIsLoad, "no");
		if (is.equals("yes")) {
			MySharedPreferences.getMySharedPreferences(mContext).setValue(
					Cache.ART_CACHE + userPhone, "");
			isRefreshed = true;
			MySharedPreferences.getMySharedPreferences(mContext).setValue(
					Cache.artIsLoad, "no");
			reqAtristListNumData();
		}
	}

	/**
	 * @Title: reqAtristListNumData
	 * @Description: TODO 获得备案数量
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	private void reqAtristListNumData() {
		// AlertUtils.showLoding(mContext);
		VolleyBasic.getInstance(ArtRecordActivity.this).post(true, false,
				Cache.artrecordstatelist,
				VolleyMap.getInstance().artRecordstatelist(),
				ArtRecordstate.class, new VolleyCallback() {

					@SuppressWarnings("unchecked")
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						ArtRecordstate item = (ArtRecordstate) vd.getData();
						String audit = item.getAuditnum();
						String notth = item.getNotthroughnum();
						String already = item.getAlreadyrecordnum();
						doing.setText("审核中(" + audit + ")");
						norecord.setText("未通过审核(" + notth + ")");
						torecord.setText("已备案(" + already + ")");
						if (audit.equals("0")) {
							doing.setVisibility(View.GONE);
						} else if (notth.equals("0")) {
							norecord.setVisibility(View.GONE);
						} else if (already.equals("0")) {
							torecord.setVisibility(View.GONE);
						}
						reqAtristListData("");// 备案列表
					}

					@Override
					public void onError(VolleyError volleyError) {
						// AlertUtils.disMissLoding();
					}
				});
	}

	/**
	 * 备案列表
	 * 
	 * @param type
	 */
	void reqAtristListData(String type) {
		AlertUtils.showLoding(mContext);
		VolleyBasic.getInstance(ArtRecordActivity.this).post(false, true,
				Cache.recordlist,
				VolleyMap.getInstance().recordList(type, page + "", "5", ""),
				RecordList.class, new VolleyCallback() {
					@SuppressWarnings("unchecked")
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						System.out.println("vd=" + vd.getJson());
						mPullLayout.loadmoreFinish(mPullLayout.SUCCEED);
						final List<RecordList> list = (List<RecordList>) vd
								.getList();
						// String is =
						// MySharedPreferences.getMySharedPreferences(
						// mContext).getValue(Cache.artIsLoad, "no");
						// if (is.equals("yes") && more_list.size() > 0) {
						// if (list.get(0).getArt_id()
						// .equals(more_list.get(0).getArt_id())) {
						// reqAtristListData("");// 备案列表
						// return;
						// } else {
						// MySharedPreferences.getMySharedPreferences(
						// mContext).setValue(Cache.artIsLoad,
						// "no");
						// }
						//
						// } else {
						// MySharedPreferences
						// .getMySharedPreferences(mContext).setValue(
						// Cache.artIsLoad, "no");
						// }

						// String artBo = MySharedPreferences
						// .getMySharedPreferences(mContext).getValue(
						// Cache.ARTREC_STATUS, "no");
						// System.out.println("artBo=" + artBo);
						// if (artBo.equals("yes")) {
						// comNetwork();
						// }
						AlertUtils.disMissLoding();
						if (isRefreshed == true) {
							more_list.clear();
							isRefreshed = false;
						}
						if (!list.isEmpty()) {
							more_list.addAll(list);
						}
						if (more_list != null && more_list.size() != 0) {
							hint.setVisibility(View.GONE);
						} else {
							hint.setVisibility(View.VISIBLE);
							return;
						}
						if (adapter == null) {
							Map<String, String> map = NetUtils
									.getDisplayMetrics(ArtRecordActivity.this);
							adapter = new ArtRecordAdapter(mContext, map
									.get(NetUtils.DM_WIDTH));
							adapter.setdata(more_list);
							listview.setAdapter(adapter);
							listview.setFocusable(false);
							listview.setAdapter(adapter);
							listview.setOnItemClickListener(new OnItemClickListener() {
								@Override
								public void onItemClick(AdapterView<?> parent,
										View view, int position, long id) {

									Intent intent = new Intent(
											ArtRecordActivity.this,
											ArtRecordDetailActivity.class);
									intent.putExtra("id",
											more_list.get(position).getArt_id());
									intent.putExtra("state",
											more_list.get(position)
													.getRegisteredstate());
									intent.putExtra("tittle",
											more_list.get(position).getTitle());
									intent.putExtra("Is_phone",
											more_list.get(position)
													.getIs_phone());
									intent.putExtra("imgurl",
											more_list.get(position).getImgurl());
									startActivity(intent);

								}
							});

						}
						adapter.notifyDataSetChanged();
					}

					@Override
					public void onError(VolleyError volleyError) {
						AlertUtils.disMissLoding();
						mPullLayout.loadmoreFinish(mPullLayout.FAIL);
						if (more_list != null && more_list.size() != 0) {
							hint.setVisibility(View.GONE);
						} else {
							hint.setVisibility(View.VISIBLE);
							return;
						}
					}
				});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.title_text:
			if (type.getVisibility() == View.VISIBLE) {
				type.setVisibility(View.GONE);

				Resources res = getResources();
				Drawable myImage = res.getDrawable(R.drawable.jzsx_btn_down);
				title_text.setCompoundDrawablesWithIntrinsicBounds(null, null,
						myImage, null);

			} else {
				type.setVisibility(View.VISIBLE);
				Resources res = getResources();
				Drawable myImage = res.getDrawable(R.drawable.jzsx_btn_up);
				title_text.setCompoundDrawablesWithIntrinsicBounds(null, null,
						myImage, null);
			}
			break;
		case R.id.all:
			reqAtristListType = "";
			page = 1;
			isRefreshed = true;
			reqAtristListData("");
			type.setVisibility(View.GONE);
			Resources res = getResources();
			Drawable myImage = res.getDrawable(R.drawable.jzsx_btn_down);
			title_text.setCompoundDrawablesWithIntrinsicBounds(null, null,
					myImage, null);
			break;
		case R.id.doing:
			reqAtristListType = "1";
			page = 1;
			isRefreshed = true;
			reqAtristListData("1");
			type.setVisibility(View.GONE);
			Resources res1 = getResources();
			Drawable myImage1 = res1.getDrawable(R.drawable.jzsx_btn_down);
			title_text.setCompoundDrawablesWithIntrinsicBounds(null, null,
					myImage1, null);
			break;
		case R.id.no_record:
			reqAtristListType = "-1";
			page = 1;
			isRefreshed = true;
			reqAtristListData("-1");
			type.setVisibility(View.GONE);
			Resources res2 = getResources();
			Drawable myImage2 = res2.getDrawable(R.drawable.jzsx_btn_down);
			title_text.setCompoundDrawablesWithIntrinsicBounds(null, null,
					myImage2, null);
			break;
		case R.id.to_record:
			reqAtristListType = "2";
			page = 1;
			isRefreshed = true;
			reqAtristListData("2");
			type.setVisibility(View.GONE);
			Resources res3 = getResources();
			Drawable myImage3 = res3.getDrawable(R.drawable.jzsx_btn_down);
			title_text.setCompoundDrawablesWithIntrinsicBounds(null, null,
					myImage3, null);
			break;
		case R.id.back_btn:
			finish();
			break;
		case R.id.rel_filing_options:
			exitPlus();
			break;
		case R.id.title_right:
			openPlus();
			break;
		case R.id.rel_p:
			ScaleAnimation scaleAnimation = new ScaleAnimation(1, 1.3f, 1,
					1.3f, Animation.RELATIVE_TO_SELF, 0.5f,
					Animation.RELATIVE_TO_SELF, 0.5f);
			AlphaAnimation alphaAnimation1 = new AlphaAnimation(1f, 0f);
			scaleAnimation.setDuration(300);//
			alphaAnimation1.setDuration(300);//
			AnimationSet set = new AnimationSet(true);
			set.addAnimation(scaleAnimation);
			set.addAnimation(alphaAnimation1);
			set.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation arg0) {
					// TODO Auto-generated method stub
					Intent intent1 = new Intent(ArtRecordActivity.this,
							GroupPhotoActivity.class);
					// intent1.putExtra("type", _PHONE);
					MySharedPreferences.getMySharedPreferences(mContext)
							.setValue(Cache.ART_TYPE, _PHONE);
					startActivity(intent1);
				}

				@Override
				public void onAnimationRepeat(Animation arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation arg0) {
					// TODO Auto-generated method stub

					optionsLayout.setVisibility(View.GONE);
				}
			});
			phoneOption.startAnimation(set);

			// comNetwork();
			break;
		case R.id.rel_m:
			ScaleAnimation scaleAnimationD = new ScaleAnimation(1, 1.3f, 1,
					1.3f, Animation.RELATIVE_TO_SELF, 0.5f,
					Animation.RELATIVE_TO_SELF, 0.5f);
			AlphaAnimation alphaAnimationD = new AlphaAnimation(1f, 0f);
			scaleAnimationD.setDuration(300);//
			alphaAnimationD.setDuration(300);//
			AnimationSet setD = new AnimationSet(true);
			setD.addAnimation(scaleAnimationD);
			setD.addAnimation(alphaAnimationD);
			setD.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation arg0) {
					// TODO Auto-generated method stub
					Intent intent2 = new Intent(ArtRecordActivity.this,
							GroupPhotoActivity.class);
					// intent2.putExtra("type", _FILING);
					MySharedPreferences.getMySharedPreferences(mContext)
							.setValue(Cache.ART_TYPE, _FILING);
					startActivity(intent2);
				}

				@Override
				public void onAnimationRepeat(Animation arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation arg0) {
					// TODO Auto-generated method stub

					optionsLayout.setVisibility(View.GONE);
				}
			});
			filingOption.startAnimation(setD);

			// comNetwork();
			break;

		default:
			break;
		}
	}

	/**
	 * 加号打开动画
	 */
	private void openPlus() {
		optionsLayout.setVisibility(View.VISIBLE);
		// 初始化
		Animation translateAnimation1 = new TranslateAnimation(0f, 0f,
				NetUtils.dip2px(this, 500), 0f);
		translateAnimation1.setDuration(500); // 设置动画时间
		Animation translateAnimation2 = new TranslateAnimation(0f, 0f,
				NetUtils.dip2px(this, 500), 0f);
		translateAnimation2.setDuration(500); // 设置动画时间
		RotateAnimation animation = new RotateAnimation(460f, 0f,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1.0f);
		alphaAnimation.setDuration(500);// 设置动画持续时间
		animation.setDuration(500);// 设置动画持续时间
		AnimationSet set = new AnimationSet(true);
		set.setInterpolator(new AccelerateDecelerateInterpolator());
		set.addAnimation(alphaAnimation);
		set.addAnimation(animation);
		// set.setDuration(500);
		llOption.startAnimation(translateAnimation1);
		optionClear.startAnimation(set);
	}

	/**
	 * 加号关闭动画
	 */
	private void exitPlus() {
		optionsLayout.setVisibility(View.VISIBLE);
		// 初始化
		Animation translateAnimation2 = new TranslateAnimation(0f, 0f, 0f,
				NetUtils.dip2px(this, 500));
		translateAnimation2.setDuration(500); // 设置动画时间
		RotateAnimation animation = new RotateAnimation(0f, 460f,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0f);
		alphaAnimation.setDuration(500);// 设置动画持续时间
		animation.setDuration(500);// 设置动画持续时间
		AnimationSet set = new AnimationSet(true);
		set.setInterpolator(new AccelerateDecelerateInterpolator());
		set.addAnimation(alphaAnimation);
		set.addAnimation(animation);
		// set.setDuration(500);
		translateAnimation2.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				// TODO Auto-generated method stub
				optionsLayout.setVisibility(View.GONE);
			}
		});
		llOption.startAnimation(translateAnimation2);
		optionClear.startAnimation(set);
	}

	void initCache() {
		JSONObject cacheJson = new JSONObject();
		try {
			cacheJson.put("art_type", "");
			cacheJson.put("title", "");
			cacheJson.put("realname", "");
			cacheJson.put("width", "");
			cacheJson.put("height", "");
			cacheJson.put("age", "");
			cacheJson.put("detail", "");
			cacheJson.put("gphoto_detail", "");
			cacheJson.put("inscribeimg", "");
			cacheJson.put("imgdata", "");
			cacheJson.put("gphotodata", "");
			cacheJson.put("dataHeight", "");
			cacheJson.put("dataWidth", "");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		MySharedPreferences.getMySharedPreferences(mContext).setValue(
				Cache.ART_CACHE + userPhone, cacheJson.toString());
	}

}
